package cn.wgx.module.sys.web;

import cn.wgx.common.base.IBaseController;
import cn.wgx.common.entity.ent.EntUser;
import cn.wgx.common.entity.sys.SysUser;
import cn.wgx.common.exception.ControllerException;
import cn.wgx.common.exception.ServiceException;
import cn.wgx.common.security.client.config.entity.LoginAppUser;
import cn.wgx.common.security.util.SysUserUtil;
import cn.wgx.common.util.ResponseDataUtil;
import cn.wgx.module.ent.service.EnterpriseService;
import cn.wgx.module.sys.service.PermissionService;
import cn.wgx.module.sys.service.UserService;
import com.alibaba.fastjson.JSONException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "1.0 用户管理")
@RestController
@RequestMapping("/api/sysUser")
public class UserCtrl extends IBaseController<UserService, SysUser> {

    @Autowired
    private PermissionService permissionService;

    @ApiOperation(value = "根据实体参数查询列表,分页查询(page第几页, limit每页数量,默认20)")
    @GetMapping("list")
    public Map list(@ModelAttribute SysUser t,
                    @RequestParam(required = false, defaultValue = "1") Integer page,
                    @RequestParam(required = false, defaultValue = "20") Integer limit) {
        Page page1 = new Page(page, limit);
        return ResponseDataUtil.returnData(page1, service.getUserList(page1, new QueryWrapper<>(t)));
    }

    @ApiIgnore
    @GetMapping(value = "/anon/getByUsername")
    @ApiOperation(value = "根据用户名查询用户")
    public LoginAppUser getByUsername(@RequestParam String username) throws ControllerException {
        try {
            LoginAppUser loginUser = service.getUserByName(username);
            return loginUser;
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }


    @ApiIgnore
    @GetMapping(value = "/anon/getByMobile")
    @ApiOperation(value = "根据用户名查询手机号")
    public LoginAppUser getByMobile(@RequestParam String mobile) throws ControllerException {
        try {
            LoginAppUser loginUser = service.getUserByMobile(mobile);
            return loginUser;
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    @ApiIgnore
    @GetMapping(value = "/anon/getUsersByIds")
    @ApiOperation(value = "根据ID列表查询用户")
    public List<SysUser> getUsersByIds(@RequestParam List<Integer> id) throws ControllerException {
        try {
            if (id == null || id.isEmpty()) {
                return ResponseDataUtil.EMPTY_LIST;
            }
            return service.getListByIds(id);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    /**
     * 当前登录用户 LoginAppUser
     *
     * @return
     * @throws ControllerException
     * @throws JsonProcessingException
     */
    @ApiIgnore
    @ApiOperation(value = "根据access_token获取当前登录用户")
    @GetMapping("/anon/getCurrentUser")
    public LoginAppUser getLoginAppUser(@RequestParam String access_token) throws ControllerException {
        try {
            LoginAppUser loginUser = SysUserUtil.getLoginAppUser(access_token);
            return loginUser;
        } catch (Exception e) {
            throw new ControllerException(e);
        }
    }

    @GetMapping("/userinfo")
    public Map getUserinfo(@RequestParam String access_token) {
        return getUser(access_token);
    }

    @GetMapping("/getuserinfo")
    public Map getUser(@RequestParam String access_token) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("code", "0");
        LoginAppUser loginUser = SysUserUtil.getLoginAppUser(access_token);
        userInfo.put("user", loginUser);
        List<String> permissions = new ArrayList<>();
        loginUser.getAuthorities().forEach(o -> {
            permissions.add(o.toString());
        });
        userInfo.put("permissions", permissions);
//        userInfo.put("ent", enterpriseService.getByEntCode());
        loginUser.setPermissions(null);
        loginUser.setSysRoles(null);
        loginUser.setMima(null);
        loginUser.setPayMima(null);
        return userInfo;
    }

    @ApiOperation(value = "根据主键ID修改实体数据,可局部修改,本接口不可修改密码")
    @PatchMapping("update")
    public Map update(@ApiParam("过滤mima，payMima") @RequestBody SysUser sysUser) {
        SysUser o = service.updateFilter(sysUser);
        LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();
        if(loginAppUser != null &&  loginAppUser.getUser_id().equals(o.getUser_id())){
            SysUserUtil.updateUserSession(null);
        }
        return ResponseDataUtil.returnData(o);
    }

    @ApiOperation(value = "更新用户状态", notes = "状态(0:正常,1:锁定,2解锁,3永久锁定),需要登录状态,不能是remember me状态. 例: {user_id:1,status:2}")
    @PatchMapping("updateStatus")
    public Map updateStatus(@RequestBody SysUser sysUser, @RequestParam String access_token) {
        if (!SysUserUtil.getLoginAppUser(access_token).getUsername().equals("admin")) {
            return ResponseDataUtil.returnErrorMap("只有admin可以更新用户状态.");
        }
        return ResponseDataUtil.returnData(service.updateStatus(sysUser));
    }

    @ApiOperation(value = "重置密码(根据用户名重置)", notes = "密码重置为‘123456’, admin可以重置所有人.")
    @RequestMapping(path = "resetMima", method = RequestMethod.PATCH)
    public Map resetMima(@RequestParam String username, @RequestParam String access_token) {
        LoginAppUser sysUser = service.getUserByName(username);
        LoginAppUser nowSysUser = SysUserUtil.getLoginAppUser(access_token);
        if (nowSysUser == null) {
            return ResponseDataUtil.returnErrorMap("请重新登陆.");
        }
        boolean flag = false;
        if (sysUser.getUser_id().equals(nowSysUser.getUser_id())) {//本人可以重置本人的
            flag = true;
        } else if (nowSysUser.getUsername().equals("admin")) {//如果是admin,则可以随便修改其他人密码
            flag = true;
        }
        if (flag) {
            int r = service.resetMima(username);
            return ResponseDataUtil.returnData(r);
        }
        return ResponseDataUtil.returnErrorMap("参数错误,或无权重置.");

    }

    @ApiOperation(value = "修改密码", notes = "RequestBody: {\"password\": \"旧密码\", \"newPassword\": \"新密码\"}")
    @PatchMapping("updateMima")
    public Map updateMima(@RequestBody Map<String, String> jsonStr, @RequestParam String access_token) {
        try {
            String password = null, newPassword = null;
            password = jsonStr.get("password");
            newPassword = jsonStr.get("newPassword");
            if (newPassword != null && newPassword.length() >= 6
                    && password != null && password.length() >= 1) {
                LoginAppUser sysUser = SysUserUtil.getLoginAppUser(access_token);
                int r = service.updateMima(sysUser.getUser_id(), password, newPassword);
                if (r == 0) {
                    return ResponseDataUtil.returnErrorMap("修改失败.旧密码错误");
                }
//                else if (r > 0) {
//                    //更新缓存
//                    UserUtil.updateSessionUser();
//                }
                return ResponseDataUtil.returnData(r);
            } else {
                return ResponseDataUtil.returnErrorMap("密码过于简单.");
            }
        } catch (JSONException e) {
            return ResponseDataUtil.returnErrorMap("jsonStr错误");
        }
    }

    @ApiOperation("获取登录用户的权限列表")
    @GetMapping("pers")
    public Map getUserPer(@RequestParam String access_token) {
        return ResponseDataUtil.returnData(permissionService.findPerByUserId(SysUserUtil.getLoginAppUser(access_token).getUser_id().longValue()));
    }

    @ApiOperation(value = "根据主键ID删除数据")
    @DeleteMapping("del/{id}")
    public Map del(@PathVariable Integer id) {
        if (id == 1) {
            return ResponseDataUtil.returnErrorMap("删除失败.admin不可以删除.");
        }
        return ResponseDataUtil.returnData(service.removeById(id));
    }

    @ApiOperation(value = "根据主键ID删除数据-批量")
    @DeleteMapping("delBatch")
    public Map delBatch(@RequestBody List<Integer> ids) {
        if (ids.contains(1)) {
            return ResponseDataUtil.returnErrorMap("删除失败.admin不可以删除.");
        }
        return ResponseDataUtil.returnData(service.removeByIds(ids));
    }

}
